/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package SubsistemaPaciente.Fichas;

import clienteSandraParada.Login;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.awt.Color;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import ordenar.Ordenar;
import service.Paciente;

/**
 *
 * @author Hernán Garrido
 */
public class FichaMedicoGeneral extends javax.swing.JPanel {

    DialogoInfoFichaMedicoGeneral dif = new DialogoInfoFichaMedicoGeneral(null, true, this);

    public FichaMedicoGeneral() throws FileNotFoundException, IOException {
        initComponents();
        this.actualizarTabla();
        this.keyListenerBuscar();
        this.ocultarColumnaID();
        this.MouseListenerTabla();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        dialogoEliminarFicha = new javax.swing.JDialog();
        jPanel8 = new javax.swing.JPanel();
        etiquetaEliminar = new javax.swing.JLabel();
        jLabel18 = new javax.swing.JLabel();
        botonSiEliminar = new javax.swing.JButton();
        botonNoEliminar = new javax.swing.JButton();
        jPanel5 = new javax.swing.JPanel();
        jLabel4 = new javax.swing.JLabel();
        buscar = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        tablaFichaFarfan = new javax.swing.JTable();
        jPanel6 = new javax.swing.JPanel();
        etiquetaMensajeria = new javax.swing.JLabel();
        jPanel7 = new javax.swing.JPanel();
        botonEliminarDerivacion = new javax.swing.JButton();
        botonModificarDerivacion = new javax.swing.JButton();
        botonVerDerivacion = new javax.swing.JButton();

        dialogoEliminarFicha.setTitle("Eliminar derivación");
        dialogoEliminarFicha.setMinimumSize(new java.awt.Dimension(420, 180));
        dialogoEliminarFicha.setModal(true);
        dialogoEliminarFicha.setResizable(false);

        etiquetaEliminar.setText("¿Confirma que desea enviar a la papelera la derivación seleccionada?");

        jLabel18.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Img/Iconos35X35/Papelera.png"))); // NOI18N

        javax.swing.GroupLayout jPanel8Layout = new javax.swing.GroupLayout(jPanel8);
        jPanel8.setLayout(jPanel8Layout);
        jPanel8Layout.setHorizontalGroup(
            jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel8Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel18)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(etiquetaEliminar)
                .addContainerGap(15, Short.MAX_VALUE))
        );
        jPanel8Layout.setVerticalGroup(
            jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel8Layout.createSequentialGroup()
                .addGap(40, 40, 40)
                .addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel18)
                    .addGroup(jPanel8Layout.createSequentialGroup()
                        .addGap(9, 9, 9)
                        .addComponent(etiquetaEliminar)))
                .addContainerGap(24, Short.MAX_VALUE))
        );

        botonSiEliminar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Img/Iconos16X16/Aceptar.png"))); // NOI18N
        botonSiEliminar.setText("Si");
        botonSiEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonSiEliminarActionPerformed(evt);
            }
        });

        botonNoEliminar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Img/Iconos16X16/Cancelar.png"))); // NOI18N
        botonNoEliminar.setText("No");
        botonNoEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonNoEliminarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout dialogoEliminarFichaLayout = new javax.swing.GroupLayout(dialogoEliminarFicha.getContentPane());
        dialogoEliminarFicha.getContentPane().setLayout(dialogoEliminarFichaLayout);
        dialogoEliminarFichaLayout.setHorizontalGroup(
            dialogoEliminarFichaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel8, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, dialogoEliminarFichaLayout.createSequentialGroup()
                .addContainerGap(225, Short.MAX_VALUE)
                .addComponent(botonSiEliminar, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(botonNoEliminar, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        dialogoEliminarFichaLayout.setVerticalGroup(
            dialogoEliminarFichaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(dialogoEliminarFichaLayout.createSequentialGroup()
                .addComponent(jPanel8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(dialogoEliminarFichaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(botonSiEliminar)
                    .addComponent(botonNoEliminar))
                .addGap(0, 15, Short.MAX_VALUE))
        );

        setPreferredSize(new java.awt.Dimension(953, 499));

        jPanel5.setBackground(new java.awt.Color(255, 255, 255));
        jPanel5.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1), "Fichas Medicina General", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.TOP, new java.awt.Font("Tahoma", 0, 36))); // NOI18N
        jPanel5.setPreferredSize(new java.awt.Dimension(953, 499));

        jLabel4.setText("Buscar ");

        tablaFichaFarfan.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "ID", "Rut paciente", "Nombre paciente", "Diagnóstico", "Fecha ingreso"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tablaFichaFarfan.getTableHeader().setReorderingAllowed(false);
        jScrollPane1.setViewportView(tablaFichaFarfan);

        javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addContainerGap(728, Short.MAX_VALUE)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(buscar, javax.swing.GroupLayout.PREFERRED_SIZE, 176, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 943, Short.MAX_VALUE)
        );
        jPanel5Layout.setVerticalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(buscar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 257, Short.MAX_VALUE)
                .addGap(58, 58, 58))
        );

        jPanel6.setBackground(new java.awt.Color(255, 255, 255));

        etiquetaMensajeria.setBackground(new java.awt.Color(255, 255, 255));
        etiquetaMensajeria.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        etiquetaMensajeria.setText("Área de mensajería");

        javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
        jPanel6.setLayout(jPanel6Layout);
        jPanel6Layout.setHorizontalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(etiquetaMensajeria, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 953, Short.MAX_VALUE)
        );
        jPanel6Layout.setVerticalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(etiquetaMensajeria, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
        );

        jPanel7.setBackground(new java.awt.Color(255, 255, 255));

        botonEliminarDerivacion.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Img/Iconos35X35/delete_32x32x32.png"))); // NOI18N
        botonEliminarDerivacion.setText("Eliminar");
        botonEliminarDerivacion.setMargin(new java.awt.Insets(2, 4, 2, 6));
        botonEliminarDerivacion.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonEliminarDerivacionActionPerformed(evt);
            }
        });

        botonModificarDerivacion.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Img/Iconos35X35/Edit.png"))); // NOI18N
        botonModificarDerivacion.setText("Modificar");
        botonModificarDerivacion.setMargin(new java.awt.Insets(2, 4, 2, 6));
        botonModificarDerivacion.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonModificarDerivacionActionPerformed(evt);
            }
        });

        botonVerDerivacion.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Img/Iconos35X35/Previsualizar.png"))); // NOI18N
        botonVerDerivacion.setText("Ver");
        botonVerDerivacion.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        botonVerDerivacion.setMargin(new java.awt.Insets(2, 4, 2, 6));
        botonVerDerivacion.setMaximumSize(new java.awt.Dimension(97, 43));
        botonVerDerivacion.setMinimumSize(new java.awt.Dimension(97, 43));
        botonVerDerivacion.setPreferredSize(new java.awt.Dimension(97, 43));
        botonVerDerivacion.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonVerDerivacionActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel7Layout = new javax.swing.GroupLayout(jPanel7);
        jPanel7.setLayout(jPanel7Layout);
        jPanel7Layout.setHorizontalGroup(
            jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel7Layout.createSequentialGroup()
                .addContainerGap(564, Short.MAX_VALUE)
                .addComponent(botonModificarDerivacion, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(botonEliminarDerivacion, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(botonVerDerivacion, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jPanel7Layout.setVerticalGroup(
            jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel7Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(botonVerDerivacion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(botonEliminarDerivacion, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(botonModificarDerivacion, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jPanel7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, 395, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
    }// </editor-fold>//GEN-END:initComponents

    public void MouseListenerTabla() {
        this.tablaFichaFarfan.addMouseListener(new MouseListener() {

            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 2) {
                    service.Privilegios p = (service.Privilegios) cargarPrivilegios(Login.getUser().getRut());
                    if (p.isVerFichaMedicinaGeneral()) {
                        normalizarEtiqueta(etiquetaMensajeria);
                        if (tablaFichaFarfan.getSelectedRow() == -1) {
                            etiquetaMensajeria.setText("Debe seleccionar una ficha para verla");
                            etiquetaMensajeria.setForeground(Color.red);
                        } else {
                            dif.setLocationRelativeTo(null);
                            dif.setTitle("Ver Ficha Clínica");
                            dif.getBotonAceptar().setText("Exportar");
                            dif.getBotonAceptar().setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Img/Iconos16X16/pdf.png")));
                            dif.getBotonCancelar().setText("Cancelar");
                            service.FichaMedicoGeneral pres = (service.FichaMedicoGeneral) obtenerFichaFarfan((Long.parseLong((String) tablaFichaFarfan.getValueAt(tablaFichaFarfan.getSelectedRow(), 0))));
                            dif.llenarCampos(pres);
                            dif.inhabilitarCampos();
                            dif.setVisible(true);
                        }
                    } else {
                        JOptionPane.showMessageDialog(null, "No tiene permisos para esta acción, \n contacte al administrador para más información");
                    }

                }
            }

            @Override
            public void mousePressed(MouseEvent e) {
            }

            @Override
            public void mouseReleased(MouseEvent e) {
            }

            @Override
            public void mouseEntered(MouseEvent e) {
            }

            @Override
            public void mouseExited(MouseEvent e) {
            }
        });
    }

    public void keyListenerBuscar() {
        this.buscar.addKeyListener(new KeyListener() {

            @Override
            public void keyTyped(KeyEvent e) {
                //realizo busqueda dinamica
            }

            @Override
            public void keyPressed(KeyEvent e) {
            }

            @Override
            public void keyReleased(KeyEvent e) {
                if (!buscar.getText().equals("")) {
                    actualizarTabla();
                    actualizarTablaBusqueda(buscar.getText());
                } else {
                    actualizarTabla();
                }
            }
        });

    }


    public void actualizarTablaBusqueda(String buscar) {
        DefaultTableModel temp = (DefaultTableModel) tablaFichaFarfan.getModel();
        for (int i = 0; i < temp.getRowCount(); i++) {
            if (!contienePalabra(buscar, temp, i)) {
                temp.removeRow(i);
                i--;
            }

        }
    }

    public boolean contienePalabra(String buscar, DefaultTableModel temp, int fila) {
        int coincidencias = 0;
        int j = 0;
        String buscarAux = buscar.toUpperCase();
        if (temp.getColumnName(0).equals("ID")) {
            j++;
        }
        for (int i = j; i < temp.getColumnCount(); i++) {
            String frase = (String) temp.getValueAt(fila, i);
            if ((frase.toUpperCase()).contains(buscarAux)) {
                coincidencias += 1; // existe una columna que coincide con la palabra buscada
            }
        }
        if (coincidencias == 0) {
            return false; // no existen coincidencias
        } else {
            return true;
        }
    }
    private void botonModificarDerivacionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonModificarDerivacionActionPerformed
        service.Privilegios p = (service.Privilegios) cargarPrivilegios(Login.getUser().getRut());
        if (p.isModificarFichaMedicinaGeneral()) {
            this.normalizarEtiqueta(etiquetaMensajeria);
            if (tablaFichaFarfan.getSelectedRow() == -1) {
                etiquetaMensajeria.setText("Debe seleccionar una Ficha para ser modificada");
                etiquetaMensajeria.setForeground(Color.red);
            } else {
                dif.setLocationRelativeTo(null);
                dif.setTitle("Modificar Ficha Clínica");
                dif.getBotonAceptar().setText("Guardar");
                dif.getBotonAceptar().setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Img/Iconos16X16/Aceptar.png")));
                dif.getBotonCancelar().setText("Cancelar");
                service.FichaMedicoGeneral far = (service.FichaMedicoGeneral) obtenerFichaFarfan((Long.parseLong((String) tablaFichaFarfan.getValueAt(tablaFichaFarfan.getSelectedRow(), 0))));
                dif.llenarCampos(far);
                dif.inhavilitarRut(); // oculto el rut al paciente
                dif.agregarFocusListenerRutPaciente();
                dif.habilitarCampos();
                dif.setVisible(true);
            }
        } else {
            JOptionPane.showMessageDialog(this, "No tiene permisos para esta acción, \n contacte al administrador para más información");
        }
    }//GEN-LAST:event_botonModificarDerivacionActionPerformed

    private void botonEliminarDerivacionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonEliminarDerivacionActionPerformed
        service.Privilegios p = (service.Privilegios) cargarPrivilegios(Login.getUser().getRut());
        if (p.isEliminarFichaMedicinaGeneral()) {
            this.normalizarEtiqueta(etiquetaMensajeria);
            int cont = 0;
            for (int i = 0; i < tablaFichaFarfan.getRowCount(); i++) {
                if (tablaFichaFarfan.isRowSelected(i)) {
                    cont++;
                }
            }
            if (cont >= 1) {
                if (cont > 1) {
                    etiquetaEliminar.setText("¿Confirma que desea enviar a la papelera las fichas seleccionadas?");
                } else if (cont == 1) {
                    etiquetaEliminar.setText("¿Confirma que desea enviar a la papelera la ficha seleccionada?");
                }
                dialogoEliminarFicha.setLocationRelativeTo(null);
                dialogoEliminarFicha.setVisible(true);

            } else {
                etiquetaMensajeria.setText("Debe seleccionar una ficha para ser eliminada");
                etiquetaMensajeria.setForeground(Color.red);
            }

        } else {
            JOptionPane.showMessageDialog(this, "No tiene permisos para esta acción, \n contacte al administrador para más información");
        }
    }//GEN-LAST:event_botonEliminarDerivacionActionPerformed

    private void botonNoEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonNoEliminarActionPerformed
        dialogoEliminarFicha.dispose();
    }//GEN-LAST:event_botonNoEliminarActionPerformed

    private void botonSiEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonSiEliminarActionPerformed
        this.normalizarEtiqueta(etiquetaMensajeria);
        for (int i = 0; i < tablaFichaFarfan.getRowCount(); i++) {
            if (tablaFichaFarfan.isRowSelected(i)) {
                service.FichaMedicoGeneral f = (service.FichaMedicoGeneral) obtenerFichaFarfan((Long.parseLong((String) tablaFichaFarfan.getValueAt(i, 0))));
                f.setValido(false);
                editarFichaFarfan(f);
                String anterior = "No aplica";
                String posterior = "Rut paciente: " + f.getRutPaciente() + "\n" + "Diagnóstico: " + f.getDiagnostico() + "\n" + "Indicaciones: " + f.getIndicaciones();
                registrar(Login.getUser(), "Ficha Médico general", "Eliminó ficha a profesional:" + f.getRutProfesional() + "de paciente :" + f.getRutPaciente(), anterior, posterior);
            }
        }
        this.actualizarTabla();
        dialogoEliminarFicha.dispose();
    }//GEN-LAST:event_botonSiEliminarActionPerformed

    private void botonVerDerivacionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonVerDerivacionActionPerformed
        service.Privilegios p = (service.Privilegios) cargarPrivilegios(Login.getUser().getRut());
        if (p.isVerFichaMedicinaGeneral()) {
            this.normalizarEtiqueta(etiquetaMensajeria);
            if (tablaFichaFarfan.getSelectedRow() == -1) {
                etiquetaMensajeria.setText("Debe seleccionar una ficha para verla");
                etiquetaMensajeria.setForeground(Color.red);
            } else {
                dif.setLocationRelativeTo(null);
                dif.setTitle("Ver Ficha Clínica");
                dif.getBotonAceptar().setText("Exportar");
                dif.getBotonAceptar().setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Img/Iconos16X16/pdf.png")));
                dif.getBotonCancelar().setText("Cancelar");
                service.FichaMedicoGeneral pres = (service.FichaMedicoGeneral) obtenerFichaFarfan((Long.parseLong((String) tablaFichaFarfan.getValueAt(tablaFichaFarfan.getSelectedRow(), 0))));
                dif.llenarCampos(pres);
                dif.inhabilitarCampos();
                dif.setVisible(true);
            }
        } else {
            JOptionPane.showMessageDialog(this, "No tiene permisos para esta acción, \n contacte al administrador para más información");
        }
    }//GEN-LAST:event_botonVerDerivacionActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton botonEliminarDerivacion;
    private javax.swing.JButton botonModificarDerivacion;
    private javax.swing.JButton botonNoEliminar;
    private javax.swing.JButton botonSiEliminar;
    private javax.swing.JButton botonVerDerivacion;
    private javax.swing.JTextField buscar;
    private javax.swing.JDialog dialogoEliminarFicha;
    private javax.swing.JLabel etiquetaEliminar;
    private javax.swing.JLabel etiquetaMensajeria;
    private javax.swing.JLabel jLabel18;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JPanel jPanel7;
    private javax.swing.JPanel jPanel8;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tablaFichaFarfan;
    // End of variables declaration//GEN-END:variables

    /**
     *@method método que borra todas las filas de la tablaFichaFarfan
     */
    public void limpiarTabla() {
        DefaultTableModel temp = (DefaultTableModel) tablaFichaFarfan.getModel();
        for (int i = tablaFichaFarfan.getRowCount() - 1; i >= 0; i--) {
            temp.removeRow(i);
        }
    }

    /**
     *@method método que recoge los pacientes desde la base de datos y actualiza la tablaPacientes
     */
    public void actualizarTabla() {
        this.limpiarTabla();
        java.util.List<service.FichaMedicoGeneral> fichas = listarFichasFarfan();
        Ordenar.ordena(fichas, "id");
        int i = 0;
        if (Login.getUser().getTipoCuenta().equals("Secretaria") || Login.getUser().getTipoCuenta().equals("Administrador")) {
            for (service.FichaMedicoGeneral p : fichas) {
                this.agregarFila();
                service.Paciente pa = (Paciente) cargarPaciente(p.getRutPaciente());
                tablaFichaFarfan.setValueAt(p.getId().toString() + "", i, 0);
                tablaFichaFarfan.setValueAt(p.getRutPaciente() + "", i, 1);
                String nombrepa = pa.getNombres() + " " + pa.getApellidoPaterno() + " " + pa.getApellidoMaterno();
                tablaFichaFarfan.setValueAt(nombrepa + "", i, 2);
                tablaFichaFarfan.setValueAt(p.getDiagnostico() + "", i, 3);
                tablaFichaFarfan.setValueAt(p.getFechaIngreso() + "", i, 4);
                i++;

            }

        } else {
            for (service.FichaMedicoGeneral p : fichas) {
                System.out.println(p.isValido());
                System.out.println(p.getRutProfesional().equals(Login.getUser().getRut()));
                if (p.isValido() && p.getRutProfesional().equals(Login.getUser().getRut())) {
                    this.agregarFila();
                    service.Paciente pa = (Paciente) cargarPaciente(p.getRutPaciente());
                    tablaFichaFarfan.setValueAt(p.getId().toString() + "", i, 0);
                    tablaFichaFarfan.setValueAt(p.getRutPaciente() + "", i, 1);
                    String nombrepa = pa.getNombres() + " " + pa.getApellidoPaterno() + " " + pa.getApellidoMaterno();
                    tablaFichaFarfan.setValueAt(nombrepa + "", i, 2);
                    tablaFichaFarfan.setValueAt(p.getDiagnostico() + "", i, 3);
                    tablaFichaFarfan.setValueAt(p.getFechaIngreso() + "", i, 4);
                    i++;
                }
            }
        }
    }

    public void ocultarColumnaID() {
        tablaFichaFarfan.getColumnModel().getColumn(0).setMaxWidth(0);
        tablaFichaFarfan.getColumnModel().getColumn(0).setMinWidth(0);
        tablaFichaFarfan.getColumnModel().getColumn(0).setPreferredWidth(0);
    }

    public void normalizarEtiqueta(JLabel label) {
        label.setText("Área de mensajería");
        label.setForeground(Color.black);
    }

    /**
     *@method método que agrega filas a la tablaPacientes
     */
    public void agregarFila() {
        DefaultTableModel temp = (DefaultTableModel) tablaFichaFarfan.getModel();
        Object nuevo[] = {"", "", "", "", ""};
        temp.addRow(nuevo);
    }

    private static Object cargarPaciente(java.lang.String rut) {
        service.PacienteWS_Service service = new service.PacienteWS_Service();
        service.PacienteWS port = service.getPacienteWSPort();
        return port.cargarPaciente(rut);
    }

    private static Long registrar(service.Usuario usuario, java.lang.String modulo, java.lang.String accion, java.lang.String valorAnterior, java.lang.String valorNuevo) {
        service.BitacoraWSService service = new service.BitacoraWSService();
        service.BitacoraWS port = service.getBitacoraWSPort();
        return port.registrar(usuario, modulo, accion, valorAnterior, valorNuevo);
    }

    private static Object cargarPrivilegios(java.lang.String rut) {
        service.PrivilegiosWS_Service service = new service.PrivilegiosWS_Service();
        service.PrivilegiosWS port = service.getPrivilegiosWSPort();
        return port.cargarPrivilegios(rut);
    }

    private static String buscarFichaFar(java.lang.String buscar, java.lang.String profesional) {
        service.FichaMedicoGeneralWSService service = new service.FichaMedicoGeneralWSService();
        service.FichaMedicoGeneralWS port = service.getFichaMedicoGeneralWSPort();
        return port.buscarFichaFar(buscar, profesional);
    }

    private static boolean agregarFichaFarfan(service.FichaMedicoGeneral fichaFarfan) {
        service.FichaMedicoGeneralWSService service = new service.FichaMedicoGeneralWSService();
        service.FichaMedicoGeneralWS port = service.getFichaMedicoGeneralWSPort();
        return port.agregarFichaFarfan(fichaFarfan);
    }

    private static boolean editarFichaFarfan(service.FichaMedicoGeneral fichaFarfan) {
        service.FichaMedicoGeneralWSService service = new service.FichaMedicoGeneralWSService();
        service.FichaMedicoGeneralWS port = service.getFichaMedicoGeneralWSPort();
        return port.editarFichaFarfan(fichaFarfan);
    }

    private static Object obtenerFichaFarfan(java.lang.Long idFicha) {
        service.FichaMedicoGeneralWSService service = new service.FichaMedicoGeneralWSService();
        service.FichaMedicoGeneralWS port = service.getFichaMedicoGeneralWSPort();
        return port.obtenerFichaFarfan(idFicha);
    }

    private static java.util.List<service.FichaMedicoGeneral> listarFichasFarfan() {
        service.FichaMedicoGeneralWSService service = new service.FichaMedicoGeneralWSService();
        service.FichaMedicoGeneralWS port = service.getFichaMedicoGeneralWSPort();
        return port.listarFichasFarfan();
    }
}
